package com.malbbmsomanager.transactions;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.malbbmsomanager.DM_BBM_InvoiceMenu;
import com.malbbmsomanager.R;
import com.malbbmsomanager.reports.DM_BBM_Reports_Generator;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class DM_BBM_CustomerInformation extends Activity implements
ActionBar.OnNavigationListener {
	// Database Name
	private static final String DBNAME = "dminvoicemanagerbbm.db";
	private static final String TAG = null;
	// Master Tables BBM
	private String FDEBTOR_TABLE = "fDebtor";
	// ****Main Transaction Table****
	private String FORDHED_TABLE = "FOrdHed";
	private String FORDDET_TABLE = "FOrdDet";
	private SQLiteDatabase mydb;
	String TagId;
	EditText etbbmcontactperson, etbbmcontacttelnumber, addressa, addressb,
			addressc;
	String CurrentRefNumber,SyncState;
	BigDecimal currentTaxAmt = new BigDecimal("0.00");

	public void onclickUpdateContactInfo(View view) {
		
		if(SyncState.equals("1")){
			AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
					DM_BBM_CustomerInformation.this);
			alertDialogBuilder.setTitle(this.getTitle());
			alertDialogBuilder
					.setMessage("Current Sales Order Already Uploaded...");
			alertDialogBuilder.setIcon(R.drawable.printinv);
			// set positive button: Yes message
			alertDialogBuilder.setPositiveButton("OK",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});
			
			AlertDialog alertDialog = alertDialogBuilder.create();
			// show alert
			alertDialog.show();
		}
		else{
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			try {
				ContentValues Update_ContactInfo = new ContentValues();
				Update_ContactInfo.put("Contact", etbbmcontactperson.getText()
						.toString());
				Update_ContactInfo.put("CusTele", etbbmcontacttelnumber.getText()
						.toString());
				Update_ContactInfo.put("CusAdd1", addressa.getText().toString());
				Update_ContactInfo.put("CusAdd2", addressb.getText().toString());
				Update_ContactInfo.put("CusAdd3", addressc.getText().toString());
				mydb.update(FORDHED_TABLE, Update_ContactInfo, " RefNo = '"
						+ CurrentRefNumber + "'", null);
			} catch (Exception e) {

			}

			AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
					DM_BBM_CustomerInformation.this);
			alertDialogBuilder.setTitle(this.getTitle());
			alertDialogBuilder
					.setMessage("Contact Details Updated Successfully...");
			alertDialogBuilder.setIcon(R.drawable.printinv);
			// set positive button: Yes message
			alertDialogBuilder.setPositiveButton("OK",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});
			// set negative button: No message
			alertDialogBuilder.setNegativeButton("EXIT",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							// cancel the alert box and put a Toast to the
							// user
							exitFromView();
							dialog.cancel();
						}
					});
			AlertDialog alertDialog = alertDialogBuilder.create();
			// show alert
			alertDialog.show();
		}
		
		
	}

	protected void exitFromView() {
		// TODO Auto-generated method stub
		Intent i = new Intent(DM_BBM_CustomerInformation.this,
				DM_BBM_InvoiceSalesOrder.class);
		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(i);
		finish();
		return;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_bbm_customer_information);

		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			TagId = bundle.getString("TAGID");
		}
		Log.v(TAG, "PRINT 01 :" + TagId);
		etbbmcontactperson = (EditText) findViewById(R.id.etbbmcontactperson);
		etbbmcontacttelnumber = (EditText) findViewById(R.id.etbbmcontacttelnumber);
		addressa = (EditText) findViewById(R.id.addressa);
		addressb = (EditText) findViewById(R.id.addressb);
		addressc = (EditText) findViewById(R.id.addressc);
		// get the action bar
		ActionBar actionBar = getActionBar();
		actionBar.setDisplayShowTitleEnabled(true);
		// Enabling Back navigation on Action Bar icon
		actionBar.setDisplayHomeAsUpEnabled(false);
		selectActiveInvoice();
		displayCutomerInfo();

	}

	private void selectActiveInvoice() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor displayHeaderSummary = null;
		try {
			if (TagId.equals("200")) {
				String queryGetSummary = "SELECT RefNo,syncHed FROM FOrdHed WHERE Active_State = '33'";
				displayHeaderSummary = mydb.rawQuery(queryGetSummary, null);
			} else {
				String queryGetSummary = "SELECT RefNo,syncHed FROM FOrdHed WHERE Active_State = '1'";
				displayHeaderSummary = mydb.rawQuery(queryGetSummary, null);
			}

			if (displayHeaderSummary != null) {
				if (displayHeaderSummary.getCount() > 0) {
					while (displayHeaderSummary.moveToNext()) {
						CurrentRefNumber = displayHeaderSummary.getString(0);// RefNo
						SyncState = displayHeaderSummary.getString(1);// RefNo
						if(SyncState.equals("1")){
							disableFields();
						}
						Log.v(TAG, "PRINT 02 :" + CurrentRefNumber);
					}
				}
			}

		} catch (Exception e) {

		}

	}



	private void disableFields() {
		// TODO Auto-generated method stub
		etbbmcontactperson.setEnabled(false);
		etbbmcontacttelnumber.setEnabled(false);
		addressa.setEnabled(false);
		addressb.setEnabled(false);
		addressc.setEnabled(false);
	}

	private void displayCutomerInfo() {
		// TODO Auto-generated method stub
		Log.v(TAG, "displayCutomerInfo");
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curcustomer = null;
		String queryIcustomer;
		try {
			queryIcustomer = "SELECT Contact,CusTele,CusAdd1,CusAdd2,CusAdd3,RefNo,Active_State from FOrdHed so Where RefNo = '"
					+ CurrentRefNumber + "'";
			curcustomer = mydb.rawQuery(queryIcustomer, null);
		} catch (Exception e) {
			Log.v(TAG, "Exception :" + e);
		}
		if (curcustomer != null) {
			if (curcustomer.getCount() > 0) {
				while (curcustomer.moveToNext()) {
					try {
						String REFNO = curcustomer.getString(5);
						Log.v(TAG, "displayCutomerInfo:" + REFNO);
						String Contact = curcustomer.getString(0);
						String CusTele = curcustomer.getString(1);
						String DebAdd1 = curcustomer.getString(2);
						String DebAdd2 = curcustomer.getString(3);
						String DebAdd3 = curcustomer.getString(4);

						etbbmcontactperson.setText(Contact);
						addressa.setText(DebAdd1);
						addressb.setText(DebAdd2);
						addressc.setText(DebAdd3);
						etbbmcontacttelnumber.setText(CusTele);
					} catch (Exception e) {
						Log.v(TAG, "Exception :" + e);
					}

				}
			} else {
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_BBM_CustomerInformation.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("INVALID CUSTOMER");
				// Setting Dialog Message
				alertDialog.setMessage("Please Select Customer..");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								alertDialog.dismiss();
							}
						});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				return;
			}
		}
		listTaxDetails();
	}

	private void listTaxDetails() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.dminvtaxinfodetlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2", "coldes_3",
				"coldes_4" };
		int[] totrdes = new int[] { R.id.grid_value_a, R.id.grid_value_b,
				R.id.grid_value_c, R.id.grid_value_d };

		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curTaxDet = null;
		String queryTaxDetails;

		try {
			queryTaxDetails = "SELECT RefNo ,TaxCode,TaxComCode FROM FOrdTaxDt WHERE RefNo ='" + CurrentRefNumber + "' GROUP BY TaxComCode";
			curTaxDet = mydb.rawQuery(queryTaxDetails, null);
		} catch (Exception e) {
			Log.v(TAG, "Exception :" + e);
		}

		if (curTaxDet != null) {
			if (curTaxDet.getCount() > 0) {
				while (curTaxDet.moveToNext()) {
					currentTaxAmt = new BigDecimal("0.00");
					String TaxCode = curTaxDet.getString(1);
					String TaxComCode = curTaxDet.getString(2);
					String TaxRegNo = null;
					String TaxName = null;
					
					Cursor curTaxDetSum = null;
					String queryTaxDetailsSum;
					try {
						queryTaxDetailsSum = "SELECT RefNo,TaxCode,TaxComCode,TaxDetAmt FROM FOrdTaxDt WHERE RefNo ='"
								+ CurrentRefNumber
								+ "' AND TaxComCode = '"
								+ TaxComCode + "'";
						curTaxDetSum = mydb.rawQuery(queryTaxDetailsSum, null);
					} catch (Exception e) {
						Log.v(TAG, "Exception :" + e);
					}
					
					if (curTaxDetSum != null) {
						if (curTaxDetSum.getCount() > 0) {
							while (curTaxDetSum.moveToNext()) {
								String TaxDetAmt = curTaxDetSum.getString(3);

								BigDecimal CurrentTaxVal = new BigDecimal(
										TaxDetAmt);
								currentTaxAmt = currentTaxAmt
										.add(CurrentTaxVal);
							}
						}
					}
					
					
					Cursor curTaxRegSum = null;
					String queryTaxRegisterSum;
					try {
						queryTaxRegisterSum = "SELECT TaxRegNo,RefNo FROM FOrdTaxRg WHERE RefNo ='" + CurrentRefNumber + "'";
						curTaxRegSum = mydb.rawQuery(queryTaxRegisterSum, null);
					} catch (Exception e) {
						Log.v(TAG, "Exception :" + e);
					}
					if (curTaxRegSum != null) {
						if (curTaxRegSum.getCount() > 0) {
							while (curTaxRegSum.moveToNext()) {
								TaxRegNo = curTaxRegSum.getString(0);
							}
						}
					}
					
					
					Cursor curfTaxRegSum = null;
					String queryfTaxRegisterSum;
					try {
						queryfTaxRegisterSum = "SELECT TaxCode,TaxName FROM fTax WHERE TaxCode ='" + TaxCode + "'";
						curfTaxRegSum = mydb.rawQuery(queryfTaxRegisterSum, null);
					} catch (Exception e) {
						Log.v(TAG, "Exception :" + e);
					}
					if (curfTaxRegSum != null) {
						if (curfTaxRegSum.getCount() > 0) {
							while (curfTaxRegSum.moveToNext()) {
								TaxName = curfTaxRegSum.getString(1);
							}
						}
					}
					

					

					currentTaxAmt = currentTaxAmt.setScale(2,
							BigDecimal.ROUND_HALF_DOWN);
					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", TaxCode);
					maptrdes.put("coldes_2", TaxName);
					maptrdes.put("coldes_3", "" + currentTaxAmt);
					maptrdes.put("coldes_4", TaxRegNo);

					fillMapstrdes.add(maptrdes);

				}
			}
		}

		// fill in the grid_item layout
		SimpleAdapter adaptertrdes = new SimpleAdapter(this, fillMapstrdes,
				R.layout.dm_bbm_tax_info_raw, fromtrdes, totrdes);
		lvtypedes.setAdapter(adaptertrdes);
		mydb.close();
	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_search:
			// search action
			return true;
		case R.id.action_location_found:
			// location found
			LocationFound();
			return true;
		case R.id.action_refresh:
			// refresh
			/*
			 * refreshMenuItem = item; // load the data from server new
			 * SyncData().execute();
			 */
			return true;
		case R.id.action_help:
			// help action
			return true;
		case R.id.action_check_updates:
			// check for updates action
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void LocationFound() {
		// TODO Auto-generated method stub
		Intent i = new Intent(DM_BBM_CustomerInformation.this,
				DM_BBM_InvoiceSalesOrder.class);
		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(i);
		finish();
		return;
	}

	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		// TODO Auto-generated method stub
		return false;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main_actions, menu);
		return true;
	}
}
